package kr.hkit.powerjava.chther24.work2.dao;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import kr.hkit.powerjava.chther24.work2.vo.Derpartment;
import kr.hkit.powerjava.chther24.work3.dao.InterfaceDao;

public class DerpartmentDao implements InterfaceDao<Derpartment> {
	private ArrayList<Derpartment> lists;
	private static final String FILE_NAME = "departList.data";
	
	@Override
	public void insertItem(Derpartment item) {
		if (!lists.contains(item)){
			lists.add(item);
		}else{
			System.out.println("중복된 데이터");
		}
	}

	@Override
	public void deleteItem(Derpartment item) {
		lists.remove(item);
	}

	@Override
	public void updateItem(Derpartment item) {
		lists.set(lists.indexOf(item), item);
	}

	@Override
	public Derpartment searchItem(Derpartment item) {
		return lists.get(lists.indexOf(item));
	}

	@Override
	public void prnItemList(Comparator<Derpartment> comp) {
		if (comp == null){
			Collections.sort(lists);
		}else{
			Collections.sort(lists, comp);
		}
		for(Derpartment dept:lists){
			System.out.println(dept);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void loadFile() {
		ObjectInputStream ois=null;
		try {
			ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(FILE_NAME)));
			lists =  (ArrayList<Derpartment>) ois.readObject();
		} catch (FileNotFoundException e) {//처음 실행시켰을 경우
			try {
				new File(FILE_NAME).createNewFile();
				lists = new ArrayList<>();
			} catch (IOException e1) {}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ois != null)try{ois.close();}catch(Exception e){}
		}
	}

	@Override
	public void saveFile() {
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(FILE_NAME)));
			oos.writeObject(lists);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (oos != null)try{oos.close();}catch(Exception e){}
		}
	}

}
